import json
import os

import allure
from loguru import logger
from enum import Enum

from requests import sessions

from config.domain import URL
from utils.comment import json_dumps


class MethodEnum(Enum):
    GET = "get"
    POST = "post"
    DELETE = "delete"
    PUT = "put"


def request(method, path, isHeader=True,step="", headers={}, **kwargs):
    with sessions.Session() as session:
        url = URL + path
        # 从系统变量获取请求头，此时的请求头已添加cookies
        headers1 = json.loads(os.getenv("headers")) if isHeader else {}
        # 更新请求头参数
        headers1.update(headers)
        # allure报告添加步骤标题
        with allure.step(step):
            session = session.request(method=method, url=url, headers=headers1, **kwargs)
        title = "=" * 10 + str(step) + "=" * 30
        logger.info(
            f"{title}"
            f"\nurl: {url}\n"
            f"method: {method}\n"
            f"headers: \n{json_dumps(headers1)}\n"
            f"request: \n{json_dumps(kwargs)}\n"
            f"responses: \n{json_dumps(session.json())}"
        )
        if session.status_code == 200:
            return session
        else:
            raise RuntimeError("\n"+f"caseName: {step}\nresponseException: "+str(session.json()))



